/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.funda.xmppserver.handlers;

import com.funda.xmppserver.ComponentParser;
import com.funda.xmppserver.XMPPClient;
import com.funda.xmppserver.XMPPInfo;
import com.funda.xmppserver.mysql.DBManager;
import com.funda.xmppserver.writer.XMPPPacketWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.XMLEvent;

/**
 *
 * @author kurinchi
 */
public class MessageHandler implements ComponentParser {

    XMPPPacketWriter packetwriter;
    XMPPClient client;
    Connection conn;
    Statement smt;
    ResultSet rs;
    Boolean valid = true;
    String id;
    String type;

    public MessageHandler(XMPPPacketWriter packetwriter, XMPPClient client) {
        this.packetwriter = packetwriter;
        this.client = client;
    }

    public void parseElement(XMLStreamReader xmlReader) throws XMLStreamException {
        System.out.println("Message...");

        String to = "";
        String msg = "";
        for (int i = 0; i < xmlReader.getAttributeCount(); i++) {
            if (xmlReader.getAttributeLocalName(i).equalsIgnoreCase("to")) {
                to = xmlReader.getAttributeValue(i);
                if(!to.contains("@"))
                {
                    to=to+"@"+XMPPInfo.getHOST();
                }
            }

        }

        while (xmlReader.hasNext()) {
            xmlReader.next();
            int event = xmlReader.getEventType();

            if (event == XMLEvent.START_ELEMENT) {
                if (xmlReader.getLocalName().equalsIgnoreCase("body")) {
                    msg = xmlReader.getElementText();
                }

            }
            if (event == XMLEvent.END_ELEMENT) {
                if (xmlReader.getLocalName().equalsIgnoreCase("message")) {
                    break;
                }
            }
        }

        System.out.println("To : " + to + " msg : " + msg);
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'hh:mm:ss");
        System.out.println(sdf.format(cal.getTime()));

        //DBManager.updateChatHistory(client.getJid().toString(), to, msg, sdf.format(cal.getTime()), false);

        packetwriter.sendMessage(to, msg,sdf.format(cal.getTime()));
    }
}
